//
//  UITableView+Extension.swift
//  iOS-Com-Extensions
//
//  Created by yiwanjun on 2020/11/16.
//

import UIKit


public extension UITableView {
    ///UITableView的tableHeaderView高度自适应, 但是只有是文字自适应
    /// - Parameter header
    func setAndLayoutTableHeaderView(header: UIView) {
        self.tableHeaderView = header
        var duoHeight: CGFloat = 0
        for view in header.subviews {
            guard let label = view as? UILabel, label.numberOfLines == 0 else { continue }
            label.preferredMaxLayoutWidth = label.frame.width
            if let height = label.text?.ch_heightForComment(font: label.font, width: label.frame.width, maxHeight: UIScreen.main.bounds.height){
                duoHeight += height
            }
        }
        
        header.setNeedsLayout()
        header.layoutIfNeeded()
        var frame = header.frame
        
        let size = header.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
        frame.size = size
        frame.size.height += duoHeight
        
        header.frame = frame
        self.tableHeaderView = header
    }
}
